#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DeltaService - 脑电Delta频段过滤服务
继承自NeuroPy类，专门处理delta频段的过滤和增强功能
"""

import sys
import os
from collections import deque
import collections
import numpy as np
import time
import logging

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
if project_root not in sys.path:
    sys.path.append(project_root)

from utils.NeuroPy3 import NeuroPy
from config.config import Config
from response.BrainWaveResult import BrainWaveResult
from exception.base_exceptions import DeviceConnectionException, SignalProcessingException
from exception.exception_handler import global_exception_handler

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class DeltaService(NeuroPy):
    """
    Delta频段过滤服务类
    继承自NeuroPy，专门处理delta频段的过滤和增强功能
    """
    
    def __init__(self, port=None, filtered_delta_range=(2, 4), analysis_duration=10):
        """
        初始化DeltaService
        
        Args:
            port: 串口地址
            filtered_delta_range: Delta频段过滤范围，默认(2, 4)Hz
            analysis_duration: 分析时长(秒)，默认10秒，可动态设置
        """
        # 调用父类构造函数
        super().__init__(port)
        
        # 设置过滤的delta频段范围
        self.__filtered_delta_range = filtered_delta_range
        self.analysis_duration = analysis_duration  # 动态分析时长
        
        # 初始化过滤后的delta相关属性
        self.__filtered_delta = 0
        self.__original_delta = 0
        self.__low_freq_removed = 0  # 被过滤掉的低频部分(0.5-2Hz)
        
        # 频段配置
        self.__original_delta_range = (0.5, 4.0)  # 添加缺少的属性
        
        # 初始化原始信号缓冲区，大小根据分析时长动态计算
        buffer_size = int(Config.DEVICE_SAMPLING_RATE * self.analysis_duration)  # 分析时长*512Hz
        self.__raw_signal_buffer = collections.deque(maxlen=buffer_size)
        self.__sampling_rate = Config.DEVICE_SAMPLING_RATE  # 采样率512Hz
        self.__last_fft_time = 0
        self.__fft_interval = 1.0  # FFT分析间隔（秒），每秒分析一次
        
        # 数据收集相关属性
        self.__data_collection_buffer = []  # 存储分析时长的数据样本
        self.__collection_start_time = time.time()
        self.__collection_interval = float(self.analysis_duration)  # 使用动态分析时长
        self.__is_collecting = True
        
        # 设置rawValue回调函数，自动积累数据
        self.setCallBack("rawValue", self._on_raw_value_update_safe)
        # 设置delta回调函数，收集数据样本
        self.setCallBack("delta", self._on_delta_update_safe)
        
        logger.info(f"DeltaService初始化完成，过滤范围: {self.__filtered_delta_range}")
    
    def start(self):
        """
        重写start方法，添加错误处理和重试机制
        """
        max_retries = 3
        retry_delay = 2
        
        for attempt in range(max_retries):
            try:
                logger.info(f"尝试启动设备连接 (第{attempt + 1}次)")
                
                # 调用父类的start方法
                super().start()
                
                # 等待一段时间确保连接稳定
                time.sleep(1)
                
                # 检查线程是否正常运行
                if hasattr(self, 'threadRun') and self.threadRun:
                    logger.info("设备连接成功，数据采集线程已启动")
                    return True
                else:
                    raise DeviceConnectionException("数据采集线程启动失败")
                    
            except Exception as e:
                processing_error = SignalProcessingException(
                    f"Delta更新处理失败: {str(e)}"
                )
                global_exception_handler.handle_exception(processing_error)
                device_error = DeviceConnectionException(
                    f"设备启动失败 (第{attempt + 1}次): {str(e)}",
                    port=str(self.port) if self.port else "未知端口"
                )
                global_exception_handler.handle_exception(device_error)
                
                # 尝试清理资源
                try:
                    if hasattr(self, 'srl') and self.srl and self.srl.is_open:
                        self.srl.close()
                except:
                    pass
                
                if attempt < max_retries - 1:
                    logger.info(f"等待{retry_delay}秒后重试...")
                    time.sleep(retry_delay)
                else:
                    exception = DeviceConnectionException(f"设备启动失败，已尝试{max_retries}次，端口: {self.port}")
                    global_exception_handler.handle_exception(exception)
                    raise exception
        
        return False
    
    def _filter_delta_frequency(self, original_delta):
        """
        使用FFT分析过滤delta频段，精确去除0.5-2Hz，只保留2-4Hz部分
        
        Args:
            original_delta: 原始delta值（0.5-4Hz）
            
        Returns:
            int: 过滤后的delta值（2-4Hz）
        """
        try:
            # 必须使用FFT分析获取精确的2-4Hz功率
            low_delta, high_delta = self._perform_fft_analysis()
            if high_delta is not None and low_delta is not None:
                # 更新被过滤掉的低频部分
                self.__low_freq_removed = low_delta
                return high_delta  # 直接返回2-4Hz的功率
            else:
                # 如果FFT分析失败，返回0而不是使用比例过滤
                logger.warning("FFT分析失败，无法获取精确的2-4Hz数据")
                self.__low_freq_removed = 0
                return 0
        except Exception as e:
            processing_error = SignalProcessingException(
                f"Delta频段FFT过滤失败: {str(e)}",
                signal_type="delta_fft_filtering"
            )
            global_exception_handler.handle_exception(processing_error)
            self.__low_freq_removed = 0
            return 0
    
    def _on_raw_value_update_safe(self, raw_value):
        """
        rawValue更新时的安全回调函数，包含错误处理
        
        Args:
            raw_value: 原始脑电信号值
        """
        try:
            # 添加调试输出（每100个样本输出一次，避免刷屏）
            # if len(self.__raw_signal_buffer) % 100 == 0:
                # print(f"[DEBUG] RawValue回调: {raw_value}, 缓冲区大小: {len(self.__raw_signal_buffer)}")  # 删除DEBUG打印
            
            if raw_value is not None and isinstance(raw_value, (int, float)):
                self.__raw_signal_buffer.append(raw_value)
                
                # 如果正在收集数据且有足够的样本，触发delta计算
                if self.__is_collecting and len(self.__raw_signal_buffer) >= 512:
                    # 每512个样本（约1秒）触发一次delta计算
                    if len(self.__raw_signal_buffer) % 512 == 0:
                        self._trigger_delta_calculation()
                        
        except Exception as e:
            processing_error = SignalProcessingException(
                f"处理rawValue时出错: {str(e)}"
            )
            global_exception_handler.handle_exception(processing_error)
    
    def _trigger_delta_calculation(self):
        """
        基于rawValue数据触发delta计算和数据收集
        """
        try:
            if not self.__is_collecting:
                return
                
            # 执行FFT分析获取delta值
            low_delta, high_delta = self._perform_fft_analysis()
            
            # 检查FFT分析是否成功
            if low_delta is None or high_delta is None:
                # FFT分析失败，跳过这次计算
                return
            
            # 使用high_delta作为过滤后的delta值（2-4Hz）
            # 使用low_delta + high_delta作为原始delta值（0.5-4Hz）
            original_delta = low_delta + high_delta
            filtered_delta = high_delta
            
            # print(f"[DEBUG] 计算得到Delta: 原始={original_delta}, 过滤={filtered_delta}")  # 删除DEBUG打印
            
            current_time = time.time()
            
            # 安全获取其他脑电数据（由于设备不发送，使用默认值）
            try:
                raw_value = getattr(self, 'rawValue', 0)
                if raw_value is None:
                    raw_value = 0
                    
                theta = getattr(self, 'theta', 0)
                if theta is None:
                    theta = 0
                    
                low_alpha = getattr(self, 'lowAlpha', 0)
                if low_alpha is None:
                    low_alpha = 0
                    
                high_alpha = getattr(self, 'highAlpha', 0)
                if high_alpha is None:
                    high_alpha = 0
                    
                low_beta = getattr(self, 'lowBeta', 0)
                if low_beta is None:
                    low_beta = 0
                    
                high_beta = getattr(self, 'highBeta', 0)
                if high_beta is None:
                    high_beta = 0
                    
                low_gamma = getattr(self, 'lowGamma', 0)
                if low_gamma is None:
                    low_gamma = 0
                    
                mid_gamma = getattr(self, 'midGamma', 0)
                if mid_gamma is None:
                    mid_gamma = 0
                    
                attention = getattr(self, 'attention', 0)
                if attention is None:
                    attention = 0
                    
                meditation = getattr(self, 'meditation', 0)
                if meditation is None:
                    meditation = 0
                    
                poor_signal = getattr(self, 'poorSignal', 0)
                if poor_signal is None:
                    poor_signal = 0
                    
            except Exception as e:
                data_error = SignalProcessingException(
                    f"获取脑电数据时出错: {str(e)}",
                    signal_type="brain_wave_data_collection"
                )
                global_exception_handler.handle_exception(data_error)
                raw_value = theta = low_alpha = high_alpha = 0
                low_beta = high_beta = low_gamma = mid_gamma = 0
                attention = meditation = poor_signal = 0
            
            # 收集数据样本
            data_sample = {
                'timestamp': current_time,
                'original_delta': original_delta,  # 0.5-4Hz
                'filtered_delta': filtered_delta,  # 2-4Hz
                'raw_value': raw_value,
                'theta': theta,
                'alpha': low_alpha + high_alpha,
                'beta': low_beta + high_beta,
                'gamma': low_gamma + mid_gamma,
                'attention': attention,
                'meditation': meditation,
                'signal': poor_signal
            }
            
            self.__data_collection_buffer.append(data_sample)
            
            # 检查是否达到10秒收集时间
            if current_time - self.__collection_start_time >= self.__collection_interval:
                self._output_collected_data()
                self._reset_collection()
                
        except Exception as e:
            processing_error = SignalProcessingException(
                f"触发delta计算时出错: {str(e)}",
                signal_type="delta_calculation_trigger"
            )
            global_exception_handler.handle_exception(processing_error)
    
    def _on_raw_value_update(self, raw_value):
        """
        rawValue更新时的回调函数，自动将数据添加到缓冲区
        
        Args:
            raw_value: 原始脑电信号值
        """
        self.__raw_signal_buffer.append(raw_value)
    
    def _on_delta_update_safe(self, delta_value):
        """
        delta更新时的安全回调函数，包含错误处理
        
        Args:
            delta_value: 原始delta值
        """
        try:
            # 添加调试输出
            print(f"[DEBUG] Delta回调被调用: {delta_value}")
            
            if not self.__is_collecting:
                print(f"[DEBUG] 数据收集已停止，跳过")
                return
                
            if delta_value is None or not isinstance(delta_value, (int, float)):
                print(f"[DEBUG] Delta值无效: {delta_value}")
                return
                
            current_time = time.time()
            
            # 安全获取过滤后的delta值
            try:
                filtered_delta = self.get_filtered_delta()
            except Exception as e:
                processing_error = SignalProcessingException(
                    f"获取过滤delta值时出错: {str(e)}",
                    signal_type="filtered_delta_retrieval"
                )
                global_exception_handler.handle_exception(processing_error)
                filtered_delta = 0
            
            # 安全获取其他脑电数据
            try:
                raw_value = getattr(self, 'rawValue', 0) or 0
                theta = getattr(self, 'theta', 0) or 0
                low_alpha = getattr(self, 'lowAlpha', 0) or 0
                high_alpha = getattr(self, 'highAlpha', 0) or 0
                low_beta = getattr(self, 'lowBeta', 0) or 0
                high_beta = getattr(self, 'highBeta', 0) or 0
                low_gamma = getattr(self, 'lowGamma', 0) or 0
                mid_gamma = getattr(self, 'midGamma', 0) or 0
                attention = getattr(self, 'attention', 0) or 0
                meditation = getattr(self, 'meditation', 0) or 0
                poor_signal = getattr(self, 'poorSignal', 0) or 0
            except Exception as e:
                data_error = SignalProcessingException(
                    f"获取脑电数据时出错: {str(e)}",
                    signal_type="brain_wave_data_retrieval"
                )
                global_exception_handler.handle_exception(data_error)
                raw_value = theta = low_alpha = high_alpha = 0
                low_beta = high_beta = low_gamma = mid_gamma = 0
                attention = meditation = poor_signal = 0
            
            # 收集数据样本
            data_sample = {
                'timestamp': current_time,
                'original_delta': delta_value,  # 0.5-4Hz
                'filtered_delta': filtered_delta,  # 2-4Hz
                'raw_value': raw_value,
                'theta': theta,
                'alpha': low_alpha + high_alpha,
                'beta': low_beta + high_beta,
                'gamma': low_gamma + mid_gamma,
                'attention': attention,
                'meditation': meditation,
                'signal': poor_signal
            }
            
            self.__data_collection_buffer.append(data_sample)
            
            # 检查是否达到10秒收集时间
            if current_time - self.__collection_start_time >= self.__collection_interval:
                self._output_collected_data()
                self._reset_collection()
        except Exception as e:
            processing_error = SignalProcessingException(
                f"Delta更新处理失败: {e}",
                signal_type="delta_update_processing"
            )
            global_exception_handler.handle_exception(processing_error)
    
    def _on_delta_update(self, delta_value):
        """
        delta更新时的回调函数，收集数据样本用于批量输出
        
        Args:
            delta_value: 原始delta值
        """
        if not self.__is_collecting:
            return
            
        current_time = time.time()
        
        # 获取过滤后的delta值
        filtered_delta = self.get_filtered_delta()
        
        # 收集数据样本
        data_sample = {
            'timestamp': current_time,
            'original_delta': delta_value,  # 0.5-4Hz
            'filtered_delta': filtered_delta,  # 2-4Hz
            'raw_value': self.rawValue,
            'theta': self.theta,
            'alpha': self.lowAlpha + self.highAlpha,
            'beta': self.lowBeta + self.highBeta,
            'gamma': self.lowGamma + self.midGamma,
            'attention': self.attention,
            'meditation': self.meditation,
            'signal': self.poorSignal
        }
        
        self.__data_collection_buffer.append(data_sample)
        
        # 检查是否达到10秒收集时间
        if current_time - self.__collection_start_time >= self.__collection_interval:
            self._output_collected_data()
            self._reset_collection()
    
    def _output_collected_data(self):
        """
        输出收集到的10秒数据
        """
        if not self.__data_collection_buffer:
            return
            
        # 添加缓冲区状态信息
        buffer_size = len(self.__raw_signal_buffer)
        buffer_percentage = (buffer_size / 1280) * 100
        fft_ready = "✅" if buffer_size >= 256 else "❌"
        
        # print(f"\n=== 10秒数据收集完成，共{len(self.__data_collection_buffer)}个样本 ===")  # 删除数据收集打印
        # print(f"rawValue缓冲区状态: {buffer_size}/1280 样本 ({buffer_percentage:.1f}%)")
        # print(f"FFT分析就绪: {fft_ready} (需要≥256样本)")
        # print("时间戳 | 原始Delta(0.5-4Hz) | 过滤Delta(2-4Hz) | Raw | Theta | Alpha | Beta | Gamma | 注意力 | 冥想度 | 信号")
        # print("-" * 120)
        
        for i, sample in enumerate(self.__data_collection_buffer):
            timestamp = sample['timestamp'] - self.__collection_start_time  # 相对时间
            # print(f"{timestamp:6.1f}s | {sample['original_delta']:8d} | {sample['filtered_delta']:8d} | "
            #       f"{sample['raw_value']:4d} | {sample['theta']:5d} | {sample['alpha']:5d} | "
            #       f"{sample['beta']:4d} | {sample['gamma']:5d} | {sample['attention']:3d} | "
            #       f"{sample['meditation']:3d} | {sample['signal']:2d}")  # 删除样本详情打印
            pass
        
        # 计算统计信息
        original_deltas = [s['original_delta'] for s in self.__data_collection_buffer]
        filtered_deltas = [s['filtered_delta'] for s in self.__data_collection_buffer]
        
        # print("-" * 120)
        # print(f"原始Delta统计: 平均={np.mean(original_deltas):.0f}, 最大={max(original_deltas)}, 最小={min(original_deltas)}")  # 删除统计打印
        # print(f"过滤Delta统计: 平均={np.mean(filtered_deltas):.0f}, 最大={max(filtered_deltas)}, 最小={min(filtered_deltas)}")  # 删除统计打印
        
        # 分析过滤效果
        if np.mean(original_deltas) > 0:
            filter_reduction = (1 - np.mean(filtered_deltas)/np.mean(original_deltas))*100
            # print(f"过滤效果: 平均降低了{filter_reduction:.1f}%")  # 删除过滤效果打印
        else:
            # print(f"过滤效果: 原始Delta为0，无法计算")  # 删除过滤效果打印
            pass
            
        # 分析过滤失败的原因
        zero_filtered_count = sum(1 for d in filtered_deltas if d == 0)
        if zero_filtered_count > 0:
            # print(f"⚠️  过滤失败样本: {zero_filtered_count}/{len(filtered_deltas)} ({zero_filtered_count/len(filtered_deltas)*100:.1f}%)")  # 删除失败样本打印
            if buffer_size < 256:
                # print(f"   原因: rawValue缓冲区数据不足 ({buffer_size}/256)")  # 删除原因打印
                pass
            elif buffer_size < 1280:
                # print(f"   原因: 缓冲区未满，可能影响分析精度 ({buffer_size}/1280)")  # 删除原因打印
                pass
        
        # print("=" * 120)  # 删除分隔线打印
    
    def _reset_collection(self):
        """
        重置数据收集
        """
        self.__data_collection_buffer.clear()
        self.__collection_start_time = time.time()
        logger.info(f"开始新的10秒数据收集...")
    
    def stop_collection(self):
        """
        停止数据收集
        """
        self.__is_collecting = False
        if self.__data_collection_buffer:
            self._output_collected_data()
    
    def start_collection(self):
        """
        开始数据收集
        """
        self.__is_collecting = True
        self._reset_collection()
    
    def _perform_fft_analysis(self):
        """
        执行FFT分析，分离0.5-2Hz和2-4Hz频段
        
        Returns:
            tuple: (low_delta_power, high_delta_power) 或 (None, None)如果数据不足
        """
        try:
            # 检查缓冲区是否有足够的数据
            buffer_size = len(self.__raw_signal_buffer)
            min_samples = 256  # 需要足够的数据点以获得准确的频率分辨率
            if buffer_size < min_samples:
                return None, None
            
            # 检查是否需要执行FFT分析
            current_time = time.time()
            if current_time - self.__last_fft_time < self.__fft_interval:
                return None, None
            
            # 更新FFT时间
            self.__last_fft_time = current_time
            
            # 转换为numpy数组并预处理
            signal_data = np.array(list(self.__raw_signal_buffer))
            signal_data = signal_data - np.mean(signal_data)  # 去除直流分量
            window = np.hanning(len(signal_data))
            signal_data = signal_data * window  # 应用窗函数
            
            # 执行FFT
            fft_result = np.fft.fft(signal_data)
            fft_freq = np.fft.fftfreq(len(signal_data), 1.0 / self.__sampling_rate)
            
            # 只取正频率部分
            positive_freq_mask = fft_freq >= 0
            fft_freq = fft_freq[positive_freq_mask]
            fft_magnitude = np.abs(fft_result[positive_freq_mask])
            
            # 计算功率谱密度
            power_spectrum = fft_magnitude ** 2
            
            # 定义频段范围
            low_delta_mask = (fft_freq >= 0.5) & (fft_freq < 2.0)    # 0.5-2Hz (要过滤掉的)
            high_delta_mask = (fft_freq >= 2.0) & (fft_freq <= 4.0)  # 2-4Hz (要保留的)
            
            # 计算各频段的平均功率密度
            low_delta_power = np.mean(power_spectrum[low_delta_mask]) if np.any(low_delta_mask) else 0
            high_delta_power = np.mean(power_spectrum[high_delta_mask]) if np.any(high_delta_mask) else 0
            
            # 将功率转换为与EEG设备输出相似的数值范围
            # 使用对数缩放来压缩大的功率值
            if high_delta_power > 0:
                # 使用对数变换来获得更合理的数值范围
                high_delta_scaled = int(np.log10(high_delta_power + 1) * 1000)
                # 确保在合理范围内 (几百到几万)
                high_delta_scaled = min(max(high_delta_scaled, 100), 50000)
            else:
                high_delta_scaled = 0
                
            if low_delta_power > 0:
                low_delta_scaled = int(np.log10(low_delta_power + 1) * 1000)
                low_delta_scaled = min(max(low_delta_scaled, 100), 50000)
            else:
                low_delta_scaled = 0
            
            return low_delta_scaled, high_delta_scaled
            
        except Exception as e:
            exception = SignalProcessingException(f"FFT分析失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            return None, None
    
    def get_filtered_delta(self):
        """
        获取过滤后的Delta值（2-4Hz）
        
        Returns:
            int: 过滤后的delta值
        """
        return self.__filtered_delta
    
    def get_separated_delta_bands(self):
        """
        获取分离的Delta频段功率值
        
        Returns:
            tuple: (low_delta_power, high_delta_power)
        """
        try:
            return self._perform_fft_analysis()
        except Exception as e:
            exception = SignalProcessingException(f"获取分离Delta频段失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            return None, None
    
    # 重写delta的setter，当原始delta更新时自动计算过滤后的值
    @property
    def delta(self):
        """获取原始delta值"""
        return self.__original_delta
    
    @delta.setter
    def delta(self, value):
        """设置delta值并自动计算过滤后的值"""
        self.__original_delta = value
        self.__filtered_delta = self._filter_delta_frequency(value)
        
        # 直接设置父类的delta属性，避免重复调用setter
        if hasattr(super(), '_NeuroPy__delta'):
            super()._NeuroPy__delta = value
        
        # 手动调用回调函数
        if "delta" in self.callBacksDictionary:
            self.callBacksDictionary["delta"](value)
    
    @property
    def filtered_delta(self):
        """获取过滤后的delta值（2-4Hz）"""
        return self.__filtered_delta
    
    @filtered_delta.setter
    def filtered_delta(self, value):
        """直接设置过滤后的delta值"""
        self.__filtered_delta = value
    
    # 新增属性：被过滤掉的低频部分
    @property
    def low_freq_removed(self):
        """获取被过滤掉的低频部分（0.5-2Hz）"""
        return self.__low_freq_removed
    
    # 新增属性：过滤比例
    @property
    def filter_ratio(self):
        """获取过滤比例，基于实际FFT分析结果动态计算"""
        try:
            if self.__original_delta > 0:
                return self.__filtered_delta / self.__original_delta
            else:
                return 0.0
        except Exception as e:
            logger.warning(f"计算过滤比例失败: {e}")
            return 0.0
    
    # 新增属性：频段范围信息
    @property
    def original_delta_range(self):
        """获取原始delta频段范围"""
        return self.__original_delta_range
    
    @property
    def filtered_delta_range(self):
        """获取过滤后delta频段范围"""
        return self.__filtered_delta_range
    
    def get_delta_info(self):
        """
        获取完整的delta信息
        
        Returns:
            dict: 包含所有delta相关信息的字典
        """
        return {
            'original_delta': self.__original_delta,
            'filtered_delta': self.__filtered_delta,
            'low_freq_removed': self.__low_freq_removed,
            'filter_ratio': self.filter_ratio,  # 使用动态计算的属性
            'original_range': self.__original_delta_range,
            'filtered_range': self.__filtered_delta_range,
            'reduction_percentage': (self.__low_freq_removed / self.__original_delta * 100) if self.__original_delta > 0 else 0
        }
    
    def get_enhanced_data(self):
        """
        获取增强的脑电数据，包含过滤后的delta
        
        Returns:
            dict: 包含所有脑电数据和过滤后delta的字典
        """
        try:
            # 获取基础数据
            base_data = {
                'rawValue': self.rawValue,
                'attention': self.attention,
                'meditation': self.meditation,
                'delta': self.delta,  # 原始delta
                'theta': self.theta,
                'lowAlpha': self.lowAlpha,
                'highAlpha': self.highAlpha,
                'lowBeta': self.lowBeta,
                'highBeta': self.highBeta,
                'lowGamma': self.lowGamma,
                'midGamma': self.midGamma,
                'poorSignal': self.poorSignal,
                'blinkStrength': self.blinkStrength
            }
            
            # 添加过滤后的delta信息
            delta_info = self.get_delta_info()
            base_data.update(delta_info)
            
            return base_data
        except Exception as e:
            exception = SignalProcessingException(f"获取增强数据失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception
    
    def set_delta_callback(self, callback_function):
        """
        设置delta数据更新时的回调函数
        
        Args:
            callback_function: 回调函数，接收delta_info参数
        """
        def delta_callback_wrapper(value):
            # 当delta更新时，传递完整的delta信息给回调函数
            delta_info = self.get_delta_info()
            callback_function(delta_info)
        
        self.setCallBack("delta", delta_callback_wrapper)
    
    def process_delta_8bands(self, brain_wave_result: BrainWaveResult) -> BrainWaveResult:
        """
        处理Delta波段数据 - 8频域增强版本
        
        利用8频域数据进行更精确的Delta波段分析，特别是结合相邻频段的信息
        来提高Delta波段处理的科学性和准确性。
        
        Args:
            brain_wave_result: 脑电数据容器（包含8频域数据）
            
        Returns:
            BrainWaveResult: 处理后的脑电数据容器
        """
        try:
            # 获取8频域原始数据
            raw_delta = brain_wave_result.delta
            raw_theta = brain_wave_result.theta
            raw_low_alpha = getattr(brain_wave_result, 'low_alpha', 0)
            raw_high_alpha = getattr(brain_wave_result, 'high_alpha', 0)
            poor_signal = brain_wave_result.poorSignal
            
            # 信号质量预检查
            if poor_signal > 100:  # 信号质量很差，使用安全回退值
                processed_delta = raw_delta  # 保持原值
                status = "信号质量差，保持原值"
            else:
                # 使用8频域增强的Delta处理算法
                processed_delta = self._enhanced_delta_filter_8bands(
                    raw_delta, raw_theta, raw_low_alpha, raw_high_alpha
                )
                status = "8频域增强算法处理"
            
            # 计算频段间相关性分析
            cross_band_analysis = self._analyze_delta_cross_band_relationships(
                processed_delta, raw_theta, raw_low_alpha, raw_high_alpha
            )
            
            # 更新结果容器
            brain_wave_result.update_band('delta', processed_delta, f"DeltaService: {status}")
            brain_wave_result.add_processing_step('delta_8band_optimization', {
                'original_delta': raw_delta,
                'processed_delta': processed_delta,
                'status': status,
                'physiologically_valid': self._is_delta_physiologically_valid(processed_delta),
                'cross_band_analysis': cross_band_analysis,
                'enhancement_factor': self._calculate_delta_enhancement_factor(raw_delta, processed_delta)
            })
            
            return brain_wave_result
            
        except Exception as e:
            processing_error = SignalProcessingException(
                f"Delta 8频域处理失败: {str(e)}",
                processing_step="delta_8band_processing"
            )
            global_exception_handler.handle_exception(processing_error)
            return brain_wave_result
    
    def _enhanced_delta_filter_8bands(self, raw_delta: int, raw_theta: int, 
                                    raw_low_alpha: int, raw_high_alpha: int) -> int:
        """
        8频域增强的Delta滤波算法
        
        利用相邻频段的信息来提高Delta波段处理的准确性：
        1. Theta波段(4-8Hz)与Delta波段(0.5-4Hz)的边界效应分析
        2. Alpha波段对Delta波段的影响评估
        3. 跨频段一致性检验和异常检测
        4. 基于频段间相关性的自适应滤波
        
        Args:
            raw_delta: 原始Delta值
            raw_theta: 原始Theta值
            raw_low_alpha: 原始Low Alpha值
            raw_high_alpha: 原始High Alpha值
            
        Returns:
            int: 8频域增强处理后的Delta值
        """
        try:
            # 1. 基础生理学范围检查
            if not self._is_delta_physiologically_valid(raw_delta):
                return self._get_delta_safe_fallback_value(raw_theta, raw_low_alpha)
            
            # 2. 跨频段一致性检验
            cross_band_consistency = self._check_delta_cross_band_consistency(
                raw_delta, raw_theta, raw_low_alpha, raw_high_alpha
            )
            
            if not cross_band_consistency:
                # 使用相邻频段信息进行修正
                corrected_delta = self._delta_cross_band_correction(
                    raw_delta, raw_theta, raw_low_alpha
                )
                return corrected_delta
            
            # 3. 基于相邻频段的自适应处理
            adaptive_delta = self._apply_delta_adaptive_processing(
                raw_delta, raw_theta, raw_low_alpha, raw_high_alpha
            )
            
            return adaptive_delta
            
        except Exception as e:
            logger.warning(f"Delta 8频域滤波失败: {e}")
            return raw_delta
    
    def _is_delta_physiologically_valid(self, delta_value: int) -> bool:
        """检查Delta值是否在生理学合理范围内"""
        # Delta波的生理学合理范围（基于脑电生理学）
        physiological_range = (100, 100000)  # 更宽泛的范围
        return physiological_range[0] <= delta_value <= physiological_range[1]
    
    def _get_delta_safe_fallback_value(self, theta: int, low_alpha: int) -> int:
        """获取Delta的安全回退值"""
        try:
            # 基于相邻频段估算合理的Delta值
            if theta > 0:
                # 通常Delta值比Theta值稍高
                estimated_delta = int(theta * 1.2)
            elif low_alpha > 0:
                # 基于Low Alpha估算
                estimated_delta = int(low_alpha * 0.8)
            else:
                # 使用默认安全值
                estimated_delta = 5000
            
            # 确保在合理范围内
            return max(100, min(estimated_delta, 50000))
            
        except Exception:
            return 5000  # 默认安全值
    
    def _check_delta_cross_band_consistency(self, delta: int, theta: int, 
                                          low_alpha: int, high_alpha: int) -> bool:
        """检查Delta跨频段一致性"""
        try:
            # 检查Delta与Theta的比例关系
            if theta > 0:
                delta_theta_ratio = delta / theta
                # 正常情况下，Delta/Theta比例应在0.5-3.0之间
                if delta_theta_ratio < 0.2 or delta_theta_ratio > 5.0:
                    return False
            
            # 检查Delta与Alpha的比例关系
            total_alpha = low_alpha + high_alpha
            if total_alpha > 0:
                delta_alpha_ratio = delta / total_alpha
                # 正常情况下，Delta/Alpha比例应在0.1-2.0之间
                if delta_alpha_ratio < 0.05 or delta_alpha_ratio > 4.0:
                    return False
            
            return True
            
        except (ZeroDivisionError, ValueError):
            return True  # 如果计算失败，假设一致性正常
    
    def _delta_cross_band_correction(self, delta: int, theta: int, low_alpha: int) -> int:
        """基于相邻频段信息进行Delta值修正"""
        try:
            # 使用相邻频段的加权平均进行修正
            weights = []
            values = []
            
            if theta > 0 and self._is_delta_physiologically_valid(theta):
                weights.append(0.4)  # Theta对Delta的影响权重
                values.append(theta * 1.1)  # 经验系数
            
            if low_alpha > 0 and self._is_delta_physiologically_valid(low_alpha):
                weights.append(0.3)  # Low Alpha对Delta的影响权重
                values.append(low_alpha * 0.9)  # 经验系数
            
            # 保留部分原始值
            weights.append(0.3)
            values.append(delta)
            
            if weights:
                corrected_value = int(np.average(values, weights=weights))
                # 确保修正值在合理范围内
                return max(100, min(corrected_value, 100000))
            else:
                return delta
                
        except Exception:
            return delta
    
    def _apply_delta_adaptive_processing(self, delta: int, theta: int, 
                                       low_alpha: int, high_alpha: int) -> int:
        """应用Delta自适应处理"""
        try:
            # 基于相邻频段活动调整Delta值
            neighbor_activity = theta + low_alpha + high_alpha
            
            if neighbor_activity > 30000:  # 高活动状态
                # 在高活动状态下，Delta可能被相对抑制
                adjustment_factor = 0.95
            elif neighbor_activity < 5000:  # 低活动状态
                # 在低活动状态下，Delta可能相对突出
                adjustment_factor = 1.05
            else:
                adjustment_factor = 1.0
            
            adjusted_delta = int(delta * adjustment_factor)
            return max(100, min(adjusted_delta, 100000))
            
        except Exception:
            return delta
    
    def _analyze_delta_cross_band_relationships(self, delta: int, theta: int, 
                                              low_alpha: int, high_alpha: int) -> dict:
        """分析Delta频段间关系"""
        analysis = {
            'delta_theta_ratio': 0.0,
            'delta_low_alpha_ratio': 0.0,
            'delta_high_alpha_ratio': 0.0,
            'frequency_dominance': 'unknown',
            'cross_band_coherence': 'normal'
        }
        
        try:
            if theta > 0:
                analysis['delta_theta_ratio'] = round(delta / theta, 3)
            
            if low_alpha > 0:
                analysis['delta_low_alpha_ratio'] = round(delta / low_alpha, 3)
            
            if high_alpha > 0:
                analysis['delta_high_alpha_ratio'] = round(delta / high_alpha, 3)
            
            # 判断频率主导性
            max_band = max(delta, theta, low_alpha, high_alpha)
            if max_band == delta:
                analysis['frequency_dominance'] = 'delta_dominant'
            elif max_band == theta:
                analysis['frequency_dominance'] = 'theta_dominant'
            elif max_band == low_alpha:
                analysis['frequency_dominance'] = 'low_alpha_dominant'
            else:
                analysis['frequency_dominance'] = 'high_alpha_dominant'
            
            # 评估跨频段一致性
            if self._check_delta_cross_band_consistency(delta, theta, low_alpha, high_alpha):
                analysis['cross_band_coherence'] = 'coherent'
            else:
                analysis['cross_band_coherence'] = 'incoherent'
                
        except Exception:
            pass
        
        return analysis
    
    def _calculate_delta_enhancement_factor(self, original: int, processed: int) -> float:
        """计算Delta增强因子"""
        try:
            if original > 0:
                return round(processed / original, 3)
            return 1.0
        except Exception:
            return 1.0
    
    def print_delta_status(self):
        """打印当前delta状态信息"""
        info = self.get_delta_info()
        logger.info("=" * 60)
        # print("Delta频段状态:")  # 删除测试打印
        # print(f"  原始Delta (0.5-4Hz): {info['original_delta']}")
        # print(f"  过滤后Delta (2-4Hz): {info['filtered_delta']}")  # 删除Delta状态打印
        logger.info(f"  被过滤低频 (0.5-2Hz): {info['low_freq_removed']}")
        logger.info(f"  过滤比例: {info['filter_ratio']:.2f}")
        logger.info(f"  减少百分比: {info['reduction_percentage']:.1f}%")
        logger.info(f"  原始频段: {info['original_range']}")
        logger.info(f"  过滤后频段: {info['filtered_range']}")
        print("=" * 60)


# 使用示例
if __name__ == "__main__":
    import time
    
    # print("DeltaService测试程序")  # 删除测试程序标题
    # print("=" * 50)  # 删除分隔线
    
    # 创建DeltaService实例
    delta_service = DeltaService("COM5")
    
    try:
        # 启动设备
        logger.info("正在启动设备...")
        delta_service.start()
        logger.info("设备启动成功")
        
        # 等待设备信号稳定...
        logger.info("等待设备信号稳定...")
        time.sleep(3)
        
        # 连续获取数据
        i = 1
        while True:
            logger.info(f"--- 第 {i} 次数据采集 ---")
            
            # 打印delta状态
            delta_service.print_delta_status()
            
            # 获取FFT分离的Delta频段数据
            low_delta_fft, high_delta_fft = delta_service.get_separated_delta_bands()
            # print(f"FFT分析结果:")  # 删除FFT分析结果打印
            # print(f"  0.5-2Hz频段功率: {low_delta_fft}")
            # print(f"  2-4Hz频段功率: {high_delta_fft}")
            
            # 获取增强数据
            enhanced_data = delta_service.get_enhanced_data()
            if enhanced_data:
                logger.info("其他脑电数据:")
                for key, value in enhanced_data.items():
                    if key not in ['original_delta', 'filtered_delta', 'low_freq_removed', 
                                  'filter_ratio', 'original_range', 'filtered_range', 'reduction_percentage']:
                        logger.info(f"  {key}: {value}")
            
            time.sleep(1)
            i += 1
            
    except KeyboardInterrupt:
        logger.info("用户中断，正在停止...")
    except Exception as e:
        device_error = DeviceConnectionException(
            f"DeltaService运行错误: {str(e)}",
            port="COM5"
        )
        global_exception_handler.handle_exception(device_error)
    finally:
        # 停止设备
        delta_service.stop()
        logger.info("设备已停止")